package org.ykh.common.utils;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Enumeration;

/**
 * @author ykh
 */
public class HttpUtils {

    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }


    /**
     * 计算请求hash
     * @param request
     * @param algorithm 算法
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String requestHashing(HttpServletRequest request,String algorithm) throws NoSuchAlgorithmException {
        final String rawRequest = toRawRequest(request);
        final MessageDigest md5 = MessageDigest.getInstance(algorithm);
        final byte[] digest = md5.digest(rawRequest.getBytes(StandardCharsets.UTF_8));
        return new String(digest);
    }

    /**
     * 获取真实ip
     * @param request
     * @return
     */
    public static String ip(HttpServletRequest request){
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            // 如果是本地环回地址，也可能是容器内部访问，需要进一步判断或处理
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                // 这里可以根据实际情况决定如何处理，例如使用localhost访问时的默认策略
            }
        } else {
            // X-Forwarded-For 可能包含多个IP地址，由逗号+空格分隔，第一个非unknown的有效IP才是客户端IP
            String[] ips = ip.split(", ");
            for (String ipPart : ips) {
                if (!"unknown".equalsIgnoreCase(ipPart)) {
                    ip = ipPart;
                    break;
                }
            }
        }
        return ip;
    }

    /**
     * 系统换行符
     * Windows平台的换行符是”\r\n“，而Linux平台的换行符是”\n“
     *
     */
    private static String lineSeparator = System.getProperty("line.separator");
   /**
    * 将ServletRequest转换为原始的严格符合Http请求格式的文本
    * @param request
    * @return
    */
   public static String toRawRequest(HttpServletRequest request){
         StringBuilder raw = new StringBuilder();

       // 请求行
       raw.append( requestLine(request));
       // 请求头
        raw.append(requestHeaders(request));
       // 空行，分隔请求头和请求体
       raw.append(lineSeparator);

       // 请求体
        raw.append(requestBody(request));
       return raw.toString();

   }

    /**
     * 获取请求行
     * @param request
     * @return
     */
   public static StringBuilder requestLine(HttpServletRequest request){
       StringBuilder raw = new StringBuilder();
       raw.append(request.getMethod()).append(" ").append(request.getRequestURI()).append(" ").append(request.getProtocol()).append(lineSeparator);
       return raw;
   }

    /**
     * 获取请求头
     * @param request
     * @return
     */
   public static StringBuilder requestHeaders(HttpServletRequest request){
       StringBuilder raw = new StringBuilder();
       Enumeration<String> headerNames = request.getHeaderNames();
       while (headerNames.hasMoreElements()) {
           String headerName = headerNames.nextElement();
           raw.append(headerName).append(": ").append(request.getHeader(headerName)).append(lineSeparator);
       }
       return raw;
   }

    /**
     * 获取请求体
     * @param request
     * @return
     */
   public static StringBuilder requestBody(HttpServletRequest request){
       StringBuilder raw = new StringBuilder();

       try (
           final BufferedReader reader = request.getReader();
       ){
           String line;
           while ((line = reader.readLine()) != null) {
               raw.append(line).append(lineSeparator);
           }
       } catch (IOException e) {
           // 处理异常，例如记录日志或抛出自定义异常
           e.printStackTrace();
       }
       return raw;
   }


}
